//
//  GZFileLogger.m
//  GZLogger
//
//  Created by GR on 2018/12/20.
//  Copyright © 2018 GR. All rights reserved.
//

#import "GZFileLogger.h"
#import "GZLogItem.h"
#import "GZFileLogFormatter.h"
#import <objc/runtime.h>

@interface GZFileLogger ()

@property (nonatomic, strong) dispatch_queue_t ioQueue;

@property (nonatomic, copy) NSString *directory;

@property (nonatomic, strong) NSFileHandle *fileHandle;

@end

@implementation GZFileLogger

- (instancetype)init {
    
    self = [super init];
    if (self) {
        self.ioQueue    = dispatch_queue_create("com.gztool.gzlogger.gzfilelogger", DISPATCH_QUEUE_SERIAL);
        self.formatter  = [[GZFileLogFormatter alloc] init];
    }
    return self;
}

#pragma mark - Private
- (NSString *)directory {
    if (!_directory) {
        
        NSString *cacheDirectory    = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
        NSString *rootDirectory     = [cacheDirectory stringByAppendingPathComponent:@"GZLog"];
        
        if (![[NSFileManager defaultManager] fileExistsAtPath:rootDirectory]) {
            NSError *error = nil;
            [[NSFileManager defaultManager] createDirectoryAtPath:rootDirectory
                                      withIntermediateDirectories:YES
                                                       attributes:nil
                                                            error:&error];
            NSLog(@"error %@", error);
        }
        
        NSLog(@"rootDirectory = %@", rootDirectory);
        
        _directory = rootDirectory;
    }
    return _directory;
}

- (NSString *)filePathWithItem:(GZLogItem *)item {
    return  [[self.directory
                      stringByAppendingPathComponent:item.dataFileName]
                     stringByAppendingPathExtension:@"text"];
}

#pragma mark - GZLogger
- (void)recordLogItem:(GZLogItem *)item {
    if (!item.dataFileName.length) {
        return;
    }
    
    dispatch_async(self.ioQueue, ^{
        NSString *filePath      = [self filePathWithItem:item];
        
        FILE *file  = fopen(filePath.UTF8String, "a+");
        NSParameterAssert(file);
        if (NULL == file) {
            return;
        }
        
        NSString *formattedText = [self.formatter formattedTextWithItem:item];
        if (!formattedText.length) {
            return;
        }
        NSData *data = [formattedText dataUsingEncoding:NSUTF8StringEncoding];
        
        fwrite(data.bytes, sizeof(Byte), data.length, file);
        
        fclose(file);
    });
}

@end
